package controller;

import java.io.IOException;
import java.sql.Date;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import pojo.Photo;
import pojo.User;
import service.ImageService;
import utils.FileUtils;

@Controller
public class ImageController {

  @Autowired
  private ImageService is;
  @RequestMapping("addImg")
  public String addImage(@RequestParam("image") CommonsMultipartFile image,String image_name,HttpSession session){
    String result = "home";
    User u = (User) session.getAttribute("user");
    if(null == u){
      return "index";
    }
    Photo photo = new Photo();
    Date date = new Date(new java.util.Date().getTime());
    photo.setDate(date);
    photo.setName(image_name);
    photo.setUserID(u.getID());
    photo.setUrl(u.getUserName()+":"+UUID.randomUUID());
    this.is.addImage(photo);
    try {
      FileUtils.upload(image.getInputStream(), photo.getUrl());
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    session.setAttribute("imageList", this.is.selectImage(u.getID()));
    return result;
  }
  @RequestMapping("deleteImg")
  @ResponseBody
  public void delete(String ids,String urls,HttpSession session){
    User user = (User) session.getAttribute("user");
    if(null==user){
      return;
    }
    this.is.delete(urls, ids);
    return;
  }
}
